package com.caigou.service.impl;

import com.caigou.bean.cms.entity.*;
import com.caigou.bean.cms.param.UsersUpdateParam;
import com.caigou.bean.exam.entity.UserInfo;
import com.caigou.bean.exam.entity.Users;
import com.caigou.bean.param.StaffManageParam;
import com.caigou.bean.param.UserBaseInfoParam;
import com.caigou.bean.vo.UserBaseInfoVO;
import com.caigou.enums.FailResultEnum;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.*;
import com.caigou.mapper.exam.UserInfoMapper;
import com.caigou.mapper.exam.UsersMapper;
import com.caigou.service.IStaffManageService;
import com.caigou.util.Md5Util;
import com.caigou.util.Result;
import com.caigou.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StaffManageServiceImpl implements IStaffManageService {

    @Resource
    private UserBaseInfoMapper userBaseInfoMapper;
    @Resource
    private DepartmentDictionaryMapper departmentDictionaryMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleXwMapper userRoleXwMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserPrivilegeMapper userPrivilegeMapper;
    @Resource
    private ChannelDicMapper channelDicMapper;


    @Override
    public Result<PageInfo<UserBaseInfo>> findStaffByParam(StaffManageParam param) {
        PageHelper.startPage(param.getPage(), param.getSize());
//        List<KeyValueVO> channel = param.getChannel();


        PageInfo<UserBaseInfo> list = new PageInfo<>(userBaseInfoMapper.findStaffByParam(param));
        //添加员工管理的频道权限
        if (!CollectionUtils.isEmpty(list.getList())) {
            List<String> userIds = list.getList().stream().map(UserBaseInfo::getUserid).collect(Collectors.toList());

            System.out.println("打印出要查询的用户" + userIds);
            List<UserPrivilege> userPrivileges = userPrivilegeMapper.findUserPrivilegeByUserIds(userIds);
            //查询出权限code

            List<String> privilegeCodes = userPrivileges.stream().map(UserPrivilege::getPrivilegeCode).distinct().collect(Collectors.toList());
            //根据权限code查询权限名称
            if (!CollectionUtils.isEmpty(privilegeCodes)) {


                List<ChannelDic> channels = channelDicMapper.findChannelsByChannelValues(privilegeCodes);
                Map<String, String> channelValueNamesMap = channels.stream().collect(Collectors.toMap(ChannelDic::getChannelValue, ChannelDic::getChannelName));
                if (!CollectionUtils.isEmpty(channels)) {
                    //Map<String, UserPrivilege> userPrivilegeMap = userPrivileges.stream().collect(Collectors.toMap(UserPrivilege::getUserid, bean -> bean, (k1, k2) -> k1));
                    Map<String, List<UserPrivilege>> userPrivilegesMap = userPrivileges.stream().collect(Collectors.groupingBy(UserPrivilege::getUserid));
                    if (!CollectionUtils.isEmpty(userPrivileges)) {
                        list.getList().forEach(bean -> {

                            List<UserPrivilege> userPrivilegeList = userPrivilegesMap.get(bean.getUserid());
                            if (!CollectionUtils.isEmpty(userPrivilegeList)) {
                                List<String> privilegeCodeList = userPrivilegeList.stream().map(UserPrivilege::getPrivilegeCode).collect(Collectors.toList());
                                String privileges = privilegeCodeList.stream().filter(Objects::nonNull).map(str2 -> channelValueNamesMap.get(str2.trim())).collect(Collectors.joining(","));
                                bean.setUserChannel(StringUtils.isEmpty(privileges) ? "" : privileges);
                            } else {
                                bean.setUserChannel("");
                            }
                        });
                    }
                }
            }
        }

        return Result.success(list);
    }

    @Override
    public Result<Integer> updateStaffByParam(UserBaseInfoParam param) {
        //保存用户基础信息
        UserBaseInfo staffId = userBaseInfoMapper.findStaffByStaffId(param.getStaffId());
        if (staffId == null) {
            return Result.error(ResponseEnum.NO_FIND_STAFF);
        }

        if (!StringUtils.isEmpty(param.getDepartmentCode())) {
            DepartmentDictionary department = departmentDictionaryMapper.findDepartmentByDepartmentCode(param.getDepartmentCode());
            if (department == null) {
                return Result.error(ResponseEnum.NO_FIND_DEPARTMENT);
            }
        }


        UserBaseInfo userBaseInfo = new UserBaseInfo();
        BeanUtils.copyProperties(param, userBaseInfo);
        userBaseInfo.setId(staffId.getId());
        userBaseInfoMapper.updateByPrimaryKeySelective(userBaseInfo);

        if (!StringUtils.isEmpty(param.getRoleCode())) {
            Role role = roleMapper.findRoleByRoleCode(param.getRoleCode());
            if (role == null) {
                return Result.error(ResponseEnum.NO_FIND_ROLE);
            }
            UserRoleXw userRoleXw = userRoleXwMapper.findRoleByUserId(staffId.getUserid());
            if (userRoleXw != null) {
                UserRoleXw userRole = new UserRoleXw();
                BeanUtils.copyProperties(userRoleXw, userRole);
                userRole.setRoleCode(param.getRoleCode());
                userRoleXwMapper.updateByPrimaryKeySelective(userRole);
            } else {
                UserRoleXw userRole = new UserRoleXw();
                userRole.setRoleCode(param.getRoleCode());
                userRole.setUserid(staffId.getUserid());
                userRole.setRoleCode(param.getRoleCode());
                userRole.setCreateTime(new Date());
                userRoleXwMapper.insertSelective(userRole);
            }
        }


        //修改密码
        if (!StringUtils.isEmpty(param.getPassword())) {
            if (!param.getPassword().equals("******")) {
                //先查询用户是否注册过
                Users users = usersMapper.findUserByUserId(staffId.getUserid());
                if (users == null) {
                    return Result.error(FailResultEnum.NO_FIND_PHONE);
                }
                //生成6位随机字符串作为用户盐值
                String salt = UUIDUtil.getUUID().replaceAll("-", "").substring(0, 6);
                //创建用户
                Users user = new Users();
                user.setId(users.getId());
                //设置密码
                user.setPassword(Md5Util.MD5_32bit(Md5Util.MD5_32bit(param.getPassword(), "UTF-8") + salt, "UTF-8"));
                //获取当前时间戳
                user.setSalt(salt);
                usersMapper.updateByPrimaryKeySelective(user);
            }
        }
        return Result.success();
    }

    @Override
    public Result<UserBaseInfoVO> findStaffByStaffId(UserBaseInfoParam param) {
        UserBaseInfo userBaseInfo = null;
        UserBaseInfoVO baseInfoVO = new UserBaseInfoVO();


        if (!StringUtils.isEmpty(param.getStaffId())) {
            StaffManageParam manageParam = new StaffManageParam();
            manageParam.setStaffId(param.getStaffId());
            List<UserBaseInfo> userBaseInfos = userBaseInfoMapper.findStaffByParam(manageParam);
            if (!CollectionUtils.isEmpty(userBaseInfos)) {
                userBaseInfo = userBaseInfos.stream().findFirst().get();
            }
        } else if (!StringUtils.isEmpty(param.getPhoneNumber())) {
            StaffManageParam manageParam = new StaffManageParam();
            manageParam.setPhoneNumber(param.getPhoneNumber());
            List<UserBaseInfo> userBaseInfos = userBaseInfoMapper.findStaffByParam(manageParam);
            Users users = usersMapper.findUserByTel(param.getPhoneNumber());
            if (!CollectionUtils.isEmpty(userBaseInfos)) {
                userBaseInfo = userBaseInfos.stream().findFirst().get();
                baseInfoVO.setIsStaffed(1);
            } else {
                baseInfoVO.setIsStaffed(0);
            }
            if (users != null) {
                baseInfoVO.setIsRegistered(1);
            } else {
                baseInfoVO.setIsRegistered(0);
            }

        }

        if (userBaseInfo != null) {
            baseInfoVO.setIsStaffed(1);

            DepartmentDictionary department = departmentDictionaryMapper.findDepartmentByDepartmentCode(userBaseInfo.getDepartmentCode());
            if (department != null) {
                userBaseInfo.setDepartmentName(department.getDepartmentName());
            }

            UserRoleXw userRoleXws = userRoleXwMapper.findRolesByUserId(userBaseInfo.getUserid());
            if (userRoleXws != null) {
                Role role = roleMapper.findRoleByRoleCode(userRoleXws.getRoleCode());
                if (role != null) {
                    userBaseInfo.setRoleName(role.getRoleName());
                    userBaseInfo.setRoleCode(role.getRoleCode());
                }
            }
        }


        if (userBaseInfo != null) {
            BeanUtils.copyProperties(userBaseInfo, baseInfoVO);
            baseInfoVO.setPassword("******");
            Users users = usersMapper.findUserByUserId(userBaseInfo.getUserid());
            UserInfo userInfo = userInfoMapper.findUserInfoByUserId(userBaseInfo.getUserid());
            Date date = new Date(users.getAddTime() * 1000);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            baseInfoVO.setAddTime(dateFormat.format(date));
            baseInfoVO.setNickname(userInfo.getNickname());
            return Result.success(baseInfoVO);
        }


        return Result.success(baseInfoVO);
    }

    @Override
    public Result<String> addStaffByParam(UserBaseInfoParam param) {
        //根据手机号查询是否已有用户
        if (StringUtils.isEmpty(param.getPhoneNumber())) {
            return Result.error(ResponseEnum.NO_PHONE_NUMBER);
        }
        List<UserBaseInfo> userBaseInfos = userBaseInfoMapper.findStaffByParam(new StaffManageParam(param.getPhoneNumber()));
        if (!CollectionUtils.isEmpty(userBaseInfos)) {
            return Result.error(ResponseEnum.REPEAT_STAFF);
        }
        if (!StringUtils.isEmpty(param.getDepartmentCode())) {
            DepartmentDictionary department = departmentDictionaryMapper.findDepartmentByDepartmentCode(param.getDepartmentCode());
            if (department == null) {
                return Result.error(ResponseEnum.NO_FIND_DEPARTMENT);
            }
        }

        if (!StringUtils.isEmpty(param.getRoleCode())) {
            Role role = roleMapper.findRoleByRoleCode(param.getRoleCode());
            if (role == null) {
                return Result.error(ResponseEnum.NO_FIND_ROLE);
            }
        }

        Users userDb = usersMapper.findUserByTel(param.getPhoneNumber());
        if (userDb == null) {
            if (StringUtils.isEmpty(param.getPassword())) {
                return Result.error(ResponseEnum.NO_PASSWORD);
            }
            //生成6位随机字符串作为用户盐值
            String salt = UUIDUtil.getUUID().replaceAll("-", "").substring(0, 6);
            //创建用户
            Users user = new Users();
            user.setUserid(UUIDUtil.getUUID());
            user.setTel(param.getPhoneNumber());
            //设置密码
            user.setPassword(Md5Util.MD5_32bit(Md5Util.MD5_32bit(param.getPassword(), "UTF-8") + salt, "UTF-8"));
            //获取当前时间戳
            user.setAddTime(System.currentTimeMillis() / 1000);
            user.setSource(8L);//注册来源  1app 2pc 3weixin 4考试中心 5微信小程序 6易找标
            user.setRegisterStyle(8L);//注册方式  1手机 2微信 3qq 4微博 5微信小程序 6易找标
            user.setIsTel(1L);
            user.setSalt(salt);
            int insert = usersMapper.insert(user);
            log.info("用户注册成功={}", user);
            if (insert == 1) {
                //设置用户默认基础信息
                UserInfo userInfo = new UserInfo();
                userInfo.setUserid(user.getUserid());
                String gwNickname = "gw_" + System.currentTimeMillis();
                userInfo.setNickname(gwNickname);
                userInfo.setUserpic("https://oss.caigou2003.com/default/default.jpg");
                userInfo.setSex(0L);
                userInfo.setBirth("");
                userInfo.setLoginnum(0);
                userInfo.setOtherTel(param.getPhoneNumber());
                userInfoMapper.insertSelective(userInfo);
                log.info("用户设置基础信息成功={}", user);
                System.out.println("用户设置基础信息成功={}" + user);
            }
            userDb = user;
        }


        //UserInfo infoByUserId = userInfoMapper.findUserInfoByUserId(userDb.getUserid());

        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setUserid(userDb.getUserid());

//        if (infoByUserId!=null) {
//        userBaseInfo.setStaffId("U000000" + infoByUserId.getId());
//        }else {
//
//
//        }
        UserBaseInfo topUser = userBaseInfoMapper.findTopUser();
        Integer id = topUser.getId();
        userBaseInfo.setStaffId("U000000" + (id + 1));
        userBaseInfo.setRealName(param.getRealName());
        userBaseInfo.setDepartmentCode(param.getDepartmentCode());
        userBaseInfo.setPosition(param.getPosition());
        userBaseInfo.setPhoneNumber(param.getPhoneNumber());
        userBaseInfo.setStatus(1);
        userBaseInfo.setIsDelete(0);
        userBaseInfo.setCreateTime(new Date());
        int addNum = userBaseInfoMapper.insertSelective(userBaseInfo);
        log.info("用户={}", userBaseInfo);
        System.out.println("用户=" + userBaseInfo);

        if (addNum == 0) {
            return Result.error(ResponseEnum.REGISTER_FAIL);
        }
        if (!StringUtils.isEmpty(param.getPassword().trim())) {
            log.info("更换密码,用户信息={}", userDb);
            System.out.println("更换密码,用户信息" + userDb);
            UsersUpdateParam updateParam = new UsersUpdateParam();
            updateParam.setUserId(userDb.getUserid());
            //设置密码
            updateParam.setNewPassword(Md5Util.MD5_32bit(Md5Util.MD5_32bit(param.getPassword(), "UTF-8") + userDb.getSalt(), "UTF-8"));
            //获取当前时间戳
            usersMapper.updatePassword(updateParam);
        }

        return Result.success(userBaseInfo.getStaffId());
    }


}
